<template lang="zh">
<q-page ref="DocPage" class="bg-grey-2" :style-fn="handlePageHeight">

    <div v-show="doc.doc_name" class=" bg-grey-2 fit" style="overflow:scroll">
        <div class=" row justify-center bg-grey-2 ">
            <div :style="editorClass" class="bg-white shadow-7 " style="margin-top:35px">
                <q-menu touch-position context-menu>

                    <q-list dense style="min-width: 100px">
                        <q-item clickable @click="handleMark" v-close-popup>
                            <q-item-section>批注</q-item-section>
                        </q-item>
                        <q-item clickable v-close-popup>
                            <q-item-section>复制</q-item-section>
                        </q-item>
                        <q-item clickable v-close-popup>
                          <q-item-section>粘贴</q-item-section>
                      </q-item>
                        <q-separator />
                        <q-item clickable @click="handleGenerateScript">
                            <q-item-section>生成分镜脚本</q-item-section>
                            <!-- <q-item-section side>
                                <q-icon name="keyboard_arrow_right" />
                            </q-item-section> -->

                        </q-item>

                    </q-list>

                </q-menu>
                <div ref="container" style="height:100%">

                </div>
            </div>
        </div>
    </div>
    <div v-show="!doc.doc_name" class="fit row flex-center bg-grey-10">
        <q-icon size="80px" name="mdi-file-document-outline"></q-icon>

    </div>
    <q-page-sticky position="top" @cilck.stop expand style="height:fit-content;min-heigth:40px">
        <Toolbar class="bg-white row flex-center full-width  editor-toolbar-mobile" v-if="engine" :engine="engine" :items="items" @cilck.stop style="top:0 !important;height:fit-content" />
    </q-page-sticky>

</q-page>
</template>

<script>
import Engine, {
    $,
    EngineInterface,
    isMobile,
    View,
    Selection,
    ViewInterface,
} from "@aomao/engine";
import Redo from "@aomao/plugin-redo";
import Undo from "@aomao/plugin-undo";
import Bold from "@aomao/plugin-bold";
import Code from "@aomao/plugin-code";
import Backcolor from "@aomao/plugin-backcolor";
import Fontcolor from "@aomao/plugin-fontcolor";
import Fontsize from "@aomao/plugin-fontsize";
import Italic from "@aomao/plugin-italic";
import Underline from "@aomao/plugin-underline";
import Hr, {
    HrComponent
} from "@aomao/plugin-hr";
import Tasklist, {
    CheckboxComponent
} from "@aomao/plugin-tasklist";
import Orderedlist from "@aomao/plugin-orderedlist";
import Unorderedlist from "@aomao/plugin-unorderedlist";
import Indent from "@aomao/plugin-indent";
import Heading from "@aomao/plugin-heading";
import Strikethrough from "@aomao/plugin-strikethrough";
import Sub from "@aomao/plugin-sub";
import Sup from "@aomao/plugin-sup";
import Alignment from "@aomao/plugin-alignment";
import Quote from "@aomao/plugin-quote";
import PaintFormat from "@aomao/plugin-paintformat";
import RemoveFormat from "@aomao/plugin-removeformat";
import SelectAll from "@aomao/plugin-selectall";
import MarkRange from '@aomao/plugin-mark-range';
import {
    message,
    Modal
} from "ant-design-vue";
import Link from "am-editor-link-vue2"
import Image, {
    ImageComponent,
    ImageUploader
} from "@aomao/plugin-image";
import Table, {
    TableComponent
} from "@aomao/plugin-table";
import File, {
    FileComponent,
    FileUploader
} from "@aomao/plugin-file";
import Video, {
    VideoComponent,
    VideoUploader
} from "@aomao/plugin-video";
import Math, {
    MathComponent
} from "@aomao/plugin-math";
import Fontfamily from "@aomao/plugin-fontfamily";
import Status, {
    StatusComponent
} from "@aomao/plugin-status";
import LineHeight from "@aomao/plugin-line-height";
import Mention, {
    MentionComponent
} from "@aomao/plugin-mention";
import {
    Outline
} from '@aomao/plugin-heading';
import Embed, {
    EmbedComponent
} from '@aomao/plugin-embed';
import CodeBlock, {
    CodeBlockComponent
} from "am-editor-codeblock-vue2";
import Toolbar, {
    ToolbarPlugin,
    ToolbarComponent
} from "am-editor-toolbar-vue2";

// import {
//     withYjs,
//     YjsEditor,
//     YCursorEditor,
//     CursorStateChangeEvent,
//     CursorData
// } from '@aomao/plugin-yjs';
// import {
//     WebsocketProvider
// } from '@aomao/plugin-yjs-websocket';

import {
    updateDocContent
} from 'src/assets/api/studio/doc';
import * as Y from 'yjs'
// import { message, Modal } from "ant-design-vue";

// import AmToolbar from "assets/module/am-editor-vue2/packages/toolbar/src";
// import { plugins, cards, pluginConfig } from "assets/module/am-editor-vue2/src/components/config";
// import { GroupItemProps } from "assets/module/am-editor-vue2/packages/toolbar/src/types";

export default {
    components: {
        Toolbar,
    },
    data() {

        return {
            doc: {
                doc_name: null,
                doc_id: null,
                content: '',

            },
            mobile: isMobile,

            editorProperties: {

            },
            // 编辑器的内容
            readonly: true,

            engine: null,
            items: [],
            editorClass: {
                width: '756px',
                minHeight: '1086px',
                padding: '40px 80px'
            },
            isMerge: false,

        };

    },
    created() {
      this.pid = this.$route.params.pid;
    },
    watch: {
        doc: function (val) {
            if (val) {
                console.log(this.doc, 'docjiazai');
            }
        }
    },
    mounted() {
        if (!this.$platform.inDesktop()) {
            this.editorClass = {
                width: '100%',
                minHeight: '1086px',
                padding: '5px 10px'
            }
        }

        this.user = this.$store.state.user

        window.addEventListener("beforeunload", () => {
            this.handleUpdateDocContent()
        })
    },
    beforeDestroy() {
        console.log('销毁前存储一次');
        this.handleUpdateDocContent();
        this.$q.loading.hide();
        if (this.engine) this.engine.destroy();
    },
    methods: {
        handleMark() {
            // let range = new Range()
            // console.log(range,this.engine);
            // // console.log(range.getText());
            //   let selection = new Selection(this.engine,range);
            //   console.log(selection);
            //   selection.create()
            console.log(window.getSelection());
            // this.engine.command.execute('mark-range', 'share', 'apply','m11111111')
        },
        loadDocEngine() {
            let toolbarOptions = {
                popup: {
                    items: [
                        ['bold',
                            'italic',
                            'strikethrough',
                            'underline',
                        ],
                        ['alignment'],
                        {
                            icon: 'more',
                            items: [
                                "heading", "fontfamily", "fontsize", "fontcolor",
                                'backcolor',
                                'moremark',
                            ],
                        },
                    ],
                },
            };
            this.items = !this.$platform.inDesktop() ? [
                ["undo", "redo", "paintformat", "removeformat"],
                [{
                    type: "collapse",
                    groups: [{
                        items: [
                            "image-uploader",
                            "codeblock",
                            "table",
                            "file-uploader",
                            "video-uploader",
                            "math",
                            "status",
                            "embed",

                        ],
                    }, ],
                }, ],
                {
                    icon: "text",
                    items: [
                        "bold", "italic", "strikethrough", "underline", "moremark",

                    ],
                },

                ["alignment"],
                {
                    icon: "highlight",
                    items: [
                        "heading", "fontfamily", "fontsize", "fontcolor", "backcolor"

                    ],
                },

                {
                    icon: "more",
                    items: [

                        "link",
                        "tasklist",
                        "unorderedlist", "orderedlist",
                        "indent", "line-height",
                        "quote", "hr"
                    ],
                },

            ] : [
                [{
                    type: "collapse",
                    groups: [{
                        items: [
                            "image-uploader",
                            "codeblock",
                            "table",
                            "file-uploader",
                            "video-uploader",
                            "math",
                            "status",
                            "embed",

                            {
                                name: "audio-uploader",
                                icon: '<span style="width:23px;height:23px;display: inline-block;border:1px solid #E8E8E8;"><svg style="top: 2px;position: relative;" t="1636128560405" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="28042" width="16" height="16"><path d="M877.854 269.225l-56.805-56.806-121.726-123.079c-24.345-21.64-41.928-27.050-68.978-27.050h-451.737c-31.108 0-55.453 24.345-55.453 55.453v789.865c0 29.755 24.345 54.1 55.453 54.1h666.787c31.108 0 55.453-24.345 55.453-54.1v-584.284c0-24.345-8.115-35.165-22.993-54.1v0zM830.516 289.513h-156.891v-156.891l156.891 156.891zM856.213 907.609c0 5.409-4.057 10.821-10.821 10.821h-666.787c-6.762 0-12.172-5.409-12.172-10.821v-789.865c0-6.762 5.409-12.172 12.172-12.172 0 0 451.737 0 451.737 0v205.582c0 12.173 9.468 21.64 21.64 21.64h204.229v574.816zM723.668 413.943c-117.668-1.353-246.157 22.993-363.825 59.511-9.468 4.058-10.821 5.409-10.821 14.877v210.991c-12.172-5.409-27.050-6.762-41.927-5.409-45.985 1.353-82.503 29.755-82.503 60.862 0 31.108 36.517 55.453 82.503 52.748 45.985-2.706 82.503-29.755 82.503-60.863v-193.409c109.553-25.698 209.638-43.28 312.429-51.395v150.128c-12.173-5.409-25.698-6.762-40.576-6.762-45.985 2.706-82.503 29.755-82.503 62.215 0 31.108 36.517 55.453 82.503 52.748 44.632-2.706 82.503-29.755 82.503-60.863v-267.797c0-13.525-6.762-16.23-20.287-17.583z" p-id="28043"></path></svg><span>',
                                title: "音频",
                                search: "音频,audio",
                            },
                        ],
                    }, ],
                }, ],
                ["undo", "redo", "paintformat", "removeformat"],
                ["heading", "fontfamily", "fontsize"],
                ["bold", "italic", "strikethrough", "underline", ],
                ["fontcolor", "backcolor"],
                ["alignment"],
                ["tasklist", "indent", "line-height"],
                {
                    icon: 'more',
                    items: [
                        "moremark",
                        "unorderedlist", "orderedlist",
                        "link", "quote", "hr"
                    ],
                },

            ];

            let container = this.$refs.container;
            if (container) {
                const engine = new Engine(container, {
                    // 启用的插件
                    plugins: [CodeBlock, ToolbarPlugin, Bold, Italic, SelectAll, Strikethrough, Sub, Sup, Underline, Tasklist, Indent, Undo, Redo, Backcolor, Fontcolor, Fontsize, Code, Hr, Alignment, PaintFormat, RemoveFormat, Table, Orderedlist, Unorderedlist, Underline, Quote, Heading, Image, Math, Fontfamily, Mention, Status, LineHeight, Link, Outline, Embed, Image, Video, File, FileUploader, ImageUploader, VideoUploader, MarkRange],
                    // 启用的卡片
                    cards: [CodeBlockComponent, ToolbarComponent, HrComponent, CheckboxComponent, CompositionEvent, Comment, TableComponent, StatusComponent, MentionComponent, MathComponent, EmbedComponent, ImageComponent, VideoComponent, FileComponent, ],
                    config: {
                        [ToolbarPlugin.pluginName]: toolbarOptions,
                        "mark-range": {
                            keys: ['share']
                        }
                    }

                });
                engine.readonly = true;
                this.engine = engine;
                this.loadShareEdit()
                // 设置显示成功消息UI，默认使用 console.log
                engine.messageSuccess = (type, msg, ...args) => {
                    console.error(type, msg, ...args);
                    message.success(msg);
                };
                // 设置显示错误消息UI，默认使用 console.error
                engine.messageError = (type, error, ...args) => {
                    console.error(type, error, ...args);
                    message.error(error);
                };
                // 设置显示确认消息UI，默认无
                engine.messageConfirm = (type, msg, ...args) => {
                    console.error(type, msg, ...args);
                    return new Promise < boolean > ((resolve, reject) => {
                        Modal.confirm({
                            content: msg,
                            onOk: () => resolve(true),
                            onCancel: () => reject(),
                        });
                    });
                };
                //卡片最大化时设置编辑页面样式
                engine.on("card:maximize", () => {
                    $(".editor-toolbar").css("z-index", "9999").css("top", "55px");
                });
                engine.on("card:minimize", () => {
                    $(".editor-toolbar").css("z-index", "").css("top", "");
                });
                // 默认编辑器值，为了演示，这里初始化值写死，正式环境可以请求api加载
                const value = this.doc.content;
                // 非协同编辑，设置编辑器值，异步渲染后回调
                engine.setValue(value, () => {

                });

                // 监听编辑器值改变事件
                engine.on("ops", () => {
                    const value = engine.getValue();

                    console.log('只改变');
                    this.doc.content = value;
                    this.onEditorUpdate()
                    // console.log("value", value);
                    // console.log("html:", engine.getHtml());
                });
                engine.on("beforeSetValue", () => {
                    console.log('设置值之前');
                    let select = document.getSelection();
                    this.select = select;
                    this.node = select.focusNode;
                    this.offset = select.focusOffset;

                    // // let range = select.createRange()

                    console.log('光标', select);
                    // const value = engine.getValue();
                    // this.doc.content = engine.getHtml();
                    // this.onEditorUpdate()
                    // console.log("value", value);
                    // console.log("html:", engine.getHtml());
                });
                engine.on("afterSetValue", () => {
                    console.log('设置值');
                    console.log(this.select);
                    // this.select.setPosition(this.node, this.offset)
                    // const value = engine.getValue();
                    // this.doc.content = engine.getHtml();
                    // this.onEditorUpdate()
                    // console.log("value", value);
                    // console.log("html:", engine.getHtml());
                });

                engine.on("mention:default", () => {
                    return [{
                            key: "1",
                            name: "User1",
                            avatar: "https://avatars.githubusercontent.com/u/17873876?v=4",
                        },
                        {
                            key: "2",
                            name: "User2",
                            avatar: "https://avatars.githubusercontent.com/u/55792257?v=4",
                        },
                    ];
                });
                this.checkPermission();
                this.engine = engine;
            }
            let viewContainer = this.$refs.view;
            if (viewContainer) {
                const view = new View(viewContainer, {
                    // 启用的插件
                    plugins: [],
                    // 启用的卡片
                    // cards,
                    // // 所有的卡片配置
                    // config: pluginConfig,
                });
                this.view = view;
            }
        },
        handleGenerateScript(){
          // let value = this.engine.getJsonValue();
          // console.log(value);
           this.$router.push({path:'/script/'+this.pid+'?doc_id='+this.doc.doc_id})
        },

        loadShareEdit() {
            // 初始化 yjs doc

            // 初始化 WebsocketProvider
            // const provider = new WebsocketProvider('wss://api.yfyh.cc', this.doc.doc_id, doc, {
            //     connect: false
            // })
            const ydoc = new Y.Doc()
            const ymap = ydoc.getMap()
            this.ydoc = ydoc
            ymap.set('local', this.doc.content)

            // 比如服务器？
            this.ydocRemote = new Y.Doc()

        },

        handleSocket() {

            this.$socket.on(this.doc.doc_id, data => {
                console.log('服务端', data);
                const ymapRemote = this.ydocRemote.getMap()


                    ymapRemote.set('server', data.content)

                    // Merge changes from remote
                    const update = Y.encodeStateAsUpdate(this.ydocRemote)
                    Y.applyUpdate(this.ydoc, update)

                    // Observe that the changes have merged
                    let newContent = this.ydoc.getMap().toJSON();
                    console.log('合并后文档', newContent)
                    this.doc.content = newContent.server;
                    this.isMerge = true;
                    this.engine.setValue(this.doc.content, () => {
                        console.log('更新成功');
                    })


                // this.doc = data;
            })
        },

        handleUpdateDocContent() {
            if (this.doc.doc_id) {
                console.log('正式储存');
                updateDocContent(this.doc).then(res => {
                    console.log(res.data);
                    if (res.data.code == 1) {
                        console.log('save success');
                    }
                })
            }

        },
        handleSave() {
            console.log('save');
        },
        checkPermission() {
            if (this.user.right >= 3) {
                this.engine.readonly = false;
            }

        },
        loadContent() {
            let value = this.doc.content;
            this.engine.setValue(value, () => {

            });

        },
        autoSave() {
            this.handleSocket();

            this.i = setInterval(() => {
                // this.$storage.setItem()
                this.$emit('update:docMsg', this.$moment(new Date().getTime(), 'x').format('HH:mm:ss') + '自动保存成功')
            }, 5000)
            console.log(this.i);
        },
        handleStop() {
            this.isStopInterval = setTimeout(() => {
                clearInterval(this.i)
                this.i = null;
                this.handleUpdateDocContent()
                this.$emit('update:docMsg', '文档已云端保存')
            }, 30000)
        },
        onEditorUpdate() {

            this.$socket.emit('docEdit', this.doc, this.user)

            if (!this.i) {
                this.autoSave()
            } else {
                clearTimeout(this.isStopInterval)
            }

            console.log('change', this.doc, this.user);
            this.handleStop()

        },
        handlePageHeight(val, i) {
            console.log(val, i);
            // this.editorStyle.height = i - val - 50 + 'px';

            return {
                height: i - val + 'px'
            }

        },
    }

}
</script>

<style>
.editor_class {
    width: 756px;
    min-height: 1086px;
}

.editor-toolbar-mobile {
    bottom: auto !important;
    ;
}
</style>
